//
//  UserAccount.swift
//  weibo
//
//  Created by Mike on 15/5/13.
//  Copyright (c) 2015年 Mike. All rights reserved.
//
/*
获取token时返回的是 

Optional({
"access_token" = "2.00M3gryCOYuBLD366ee69147EbTfFC";
"expires_in" = 157679999;
"remind_in" = 157679999;
uid = 2731640032;
})

*/
import UIKit
import Alamofire
class UserAccount: NSObject, Printable, NSCoding{
    var access_token: String
    
    // 对于归档而言 这个值是没有意义的 因为是相对当前时间的过期时间 而不是1970
//    var expires_in: NSTimeInterval
    
//    var remind_in: 不建议使用了 使用expires_in
    var expiresDate: NSDate // 不是服务器返回的 需要根据expires_in计算
    
    var uid: String
    
    var name: String? // 用户的name 可以为nil， 因为是在loadUserInfo之后获得
    var avatar_large: String? // 用户头像的地址 可以为nil，因为是在loadUserInfo之后获得
    
    // 类变量 存储账户的存储路径
    static let accountPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as! String).stringByAppendingPathComponent("account.plist")
    
    init(dict: [String : AnyObject]) {
        access_token = dict["access_token"] as! String
        let expires_in = dict["expires_in"] as! NSTimeInterval
        expiresDate = NSDate(timeIntervalSinceNow: expires_in) // 根据expires_in计算过期时间
        uid = dict["uid"] as! String
    }
    
    // 重写description属性的getter 便于输出对象 打印调试（需要集成Printable）
    override var description: String {
        let propertyList = ["access_token", "expiresDate", "uid", "name", "avatar_large"]
        return "\(self.dictionaryWithValuesForKeys(propertyList))"
    }
    
    // MARK:- 归档和解档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject("avatar_large", forKey: "avatar_large")
    }
    required init(coder aDecoder: NSCoder) {
        self.access_token = aDecoder.decodeObjectForKey("access_token") as! String
        self.expiresDate = aDecoder.decodeObjectForKey("expiresDate") as! NSDate
        self.uid = aDecoder.decodeObjectForKey("uid") as! String
        
        self.name = aDecoder.decodeObjectForKey("name") as? String
        self.avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    /// 通过传递的params 加载网络请求获取token
    class func loadAccessToken(params: [String : AnyObject],complete: (account: UserAccount?, error: NSError?) -> Void) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        Alamofire.request(.POST, urlString, parameters: params).responseJSON() { (_, _, jsonObj, error)  in
            // 如果获取过程发生错误
            if error != nil {
                complete(account: nil, error: error)
                return
            }
            // 如果获取成功 ，将用户存储到沙盒
            let account = UserAccount(dict: jsonObj as! [String : AnyObject])
            
            account.loadUserInfo(complete) // 将上层传过来的complete 传递给loadUserInfo 处理错误
        }
        
    }
    /// 从沙盒加载用户信息和token
    class func loadUserAccount() -> UserAccount? {
//        return NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as! UserAccount
        // 一旦用户的过期时间到了 需要重新登录
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount {
            if account.expiresDate.compare(NSDate()) == .OrderedDescending {
                println(account)
                return account
            }
        }
        return nil
    }
    /// 根据用户的uid和token获取用户信息
<<<<<<< HEAD
    func loadUserInfo(complete: (account: UserAccount?, error: NSError?) -> Void) {
=======
    func loadUserInfo() {
>>>>>>> 5a21b90683a64f702f714894f32a03a0bd074531
        println(__FUNCTION__)
        var params: [String : String] = ["uid" : uid, "access_token" : access_token]
        
        Alamofire.request(.GET, "https://api.weibo.com/2/users/show.json", parameters: params).responseJSON() { (_, _, jsonObj, error) in
            
<<<<<<< HEAD
            if error != nil || jsonObj == nil {
                complete(account: nil, error: error)
                return
            }
            
            if let dict = jsonObj as? [String : AnyObject] {
                self.name = dict["name"] as? String
                self.avatar_large = dict["avatar_large"] as? String
                println(self)
                NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
                complete(account: self, error: nil)
            } else {
                // 发生的可能性 很小jsonObj传回的数据是错误的，或者转成[String : AnyObject]的时候出了问题
                // 需要制造一个错误 并上抛
                let err = NSError(domain: "WEIBO.parser", code: -1, userInfo: ["error":"数据解析错误"]) // 制造错误
                complete(account: nil, error: err) // 上抛
=======
            if error == nil {
                let dict = jsonObj as! [String : AnyObject]
                self.name = dict["name"] as? String
                self.avatar_large = dict["avatar_large"] as? String
                println(self)
>>>>>>> 5a21b90683a64f702f714894f32a03a0bd074531
            }
        }
    }
}
